package com.devicemantra.coordinate.jaxb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import com.devicemantra.coordinate.exceptions.jaxb.*;


/** This class reads from the ServletInputStream , unmarshalls the XML request using JAXB 
 *  and returns a new Request Object.
 * @author amith
 *
 */

public class JAXBRequestFactory {
	
	public static Request parseRequest(String pInputXmlStr) throws CJAXBException 	{
	
		Request lRequest = null;
		try {
			lRequest = unMarshallPayload(pInputXmlStr);
		} catch (CJAXBException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			throw new CJAXBException(e.getMessage() + pInputXmlStr);
		} 
	return lRequest;
}
	
	
	
	public static Request unMarshallPayload(String pInputXmlStr) throws CJAXBException
	{
		Unmarshaller lJAXBUnMarshaller = JAXBContextFactory.createUnMarshaller();
		Request lRequest = null;
		try {
			StringReader lStrReader = new StringReader(pInputXmlStr);
			JAXBElement<Request>  lJAXBRequest = (JAXBElement<Request>)lJAXBUnMarshaller.unmarshal(lStrReader);
			lRequest = lJAXBRequest.getValue();
		}catch (UnmarshalException e1) {
			// TODO Auto-generated catch block
			//e1.printStackTrace();
			throw new CJAXBException("Could not Unmarshall XML ");
		} catch (JAXBException e2) {
			// TODO Auto-generated catch block
			//e2.printStackTrace();
			throw new CJAXBException("Could not create Unmarshaller");
		} finally {
			lJAXBUnMarshaller = null;
		}
		return lRequest;
	}
	
}
